<template>
  <div>
    <el-row :gutter="20" class="flight-list">
      <el-col :span="24" v-for="(flight, index) in currentFlights" :key="index">
        <el-card shadow="hover" class="flight-card">
          <div class="flight-info">
            <img :src="flight.logoUrl" alt="Airline Logo" class="airline-logo">
            <div class="flight-details">
              <div class="flight-main-info">
                <h4>{{ flight.hbname }}</h4>
                <div>
                  <p>{{ formatTime(flight.cftime) }} - {{ formatTime(flight.ddtime) }}</p>
                  <p>{{ flight.cfcity }} - {{ flight.ddcity }}</p>
                </div>
              </div>
              <p>{{ calculateDuration(flight.cftime, flight.ddtime) }}</p>
              <p class="price">￥{{ flight.jjprice }} 起</p>
              <div class="buttons">
                <el-button type="text" @click="showDetails(index)">航班详情</el-button>
                <el-button type="primary" @click="orderFlight(index)">订购</el-button>
              </div>
            </div>
          </div>
          <el-dialog v-model="dialogVisible[index]" width="30%" :before-close="handleClose" :append-to-body="true">
            <div>
              <h3>航班详情</h3>
              <p>航班名称：{{ flight.hbname }}</p>
              <p>出发地：{{ flight.cfcity }}</p>
              <p>目的地：{{ flight.ddcity }}</p>
              <p>出发时间：{{ flight.cftime }}</p>
              <p>到达时间：{{ flight.ddtime }}</p>
              <p>经济舱票价：{{ flight.jjprice }}</p>
              <p>头等舱票价：{{ flight.tdprice }}</p>
              <p>经济舱余票：{{ flight.jjrticket }}</p>
              <p>头等舱余票：{{ flight.tdrticket }}</p>
            </div>
          </el-dialog>
          <el-dialog v-model="orderDialogVisible[index]" width="30%" :before-close="handleClose" :append-to-body="true">
            <div>
              <h3>订购航班</h3>
              <p>航班名称：{{ flight.hbname }}</p>
              <p>出发地：{{ flight.cfcity }}</p>
              <p>目的地：{{ flight.ddcity }}</p>

              <el-radio-group v-model="selectedClass">
                <el-radio label="economy">经济舱</el-radio>
                <el-radio label="firstClass">头等舱</el-radio>
              </el-radio-group>

              <p>票价：{{ selectedClass === 'economy' ? flight.jjprice : flight.tdprice }}</p>

              <el-input-number v-model="ticketCount" :min="1" :max="selectedClass === 'economy' ? flight.jjrticket : flight.tdrticket" label="选择票数"></el-input-number>

              <p>总价：{{ (selectedClass === 'economy' ? flight.jjprice : flight.tdprice) * ticketCount }}</p>

              <el-button type="primary" @click="confirmOrder(index)">确定</el-button>
            </div>
          </el-dialog>
        </el-card>
      </el-col>
    </el-row>
    <el-pagination
        background
        layout="prev, pager, next"
        :total="flights.length"
        :page-size="pageSize"
        v-model:current-page="currentPage"
        @current-change="handlePageChange"
    />
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { getFlightByCFCityAndDDCity, updateFlight } from '@/api/flight.js';
import { addOrder } from '@/api/order.js';
import { useRoute } from 'vue-router';

const logoPaths = [
  require('@/assets/images/airlogo1.png'),
  require('@/assets/images/airlogo2.png'),
  require('@/assets/images/airlogo3.png'),
  require('@/assets/images/airlogo4.png'),
  require('@/assets/images/airlogo5.png')
];

const flights = ref([]);
const dialogVisible = ref([]);
const orderDialogVisible = ref([]);
const currentPage = ref(1);
const pageSize = 5;

const route = useRoute();
const cfcity = route.query.cfcity;
const ddcity = route.query.ddcity;

const selectedClass = ref('economy');
const ticketCount = ref(1);

const userInfoString = localStorage.getItem('userInfo');
const userInfo = ref(JSON.parse(userInfoString));
const userId = userInfo.value.id;

const getRandomLogo = () => {
  const randomIndex = Math.floor(Math.random() * logoPaths.length);
  return logoPaths[randomIndex];
};

onMounted(async () => {
  try {
    const response = await getFlightByCFCityAndDDCity(cfcity, ddcity);
    if (response.code === 1) {
      flights.value = response.data.map(flight => ({
        ...flight,
        logoUrl: getRandomLogo()
      }));
      dialogVisible.value = new Array(response.data.length).fill(false);
      orderDialogVisible.value = new Array(response.data.length).fill(false);
    }
  } catch (error) {
    console.error('Error fetching flight data:', error);
  }
});

const currentFlights = computed(() => {
  const start = (currentPage.value - 1) * pageSize;
  const end = start + pageSize;
  return flights.value.slice(start, end);
});

const showDetails = (index) => {
  dialogVisible.value[index] = true;
};

const orderFlight = (index) => {
  orderDialogVisible.value[index] = true;
};

const handleClose = (done) => {
  done();
};

const handlePageChange = (page) => {
  currentPage.value = page;
};

const confirmOrder = async (index) => {
  const flight = flights.value[index];
  const selectedPrice = selectedClass.value === 'economy' ? flight.jjprice : flight.tdprice;
  const selectedTickets = selectedClass.value === 'economy' ? flight.jjrticket : flight.tdrticket;

  if (ticketCount.value > selectedTickets) {
    alert('所选余票不足，请选择更少的票数或更换舱位。');
    return;
  }

  const order = {
    orderNo: Date.now().toString() + selectedPrice.toString().replace('.', ''),
    orderTime: new Date().toISOString().slice(0, 19).replace('T', ' '),
    price: selectedPrice.toString(),
    spaceType: selectedClass.value === 'economy' ? '经济舱' : '头等舱',
    flightID: flight.id.toString(),
    userID: userId.toString(),
    buyNum: ticketCount.value.toString(),
    tprice: (selectedPrice * ticketCount.value).toString(),
    status: 'pending'
  };

  try {
    await addOrder(order);

    const updatedFlight = {
      id: flight.id,
      jjrticket: selectedClass.value === 'economy' ? (flight.jjrticket - ticketCount.value).toString() : flight.jjrticket,
      tdrticket: selectedClass.value === 'firstClass' ? (flight.tdrticket - ticketCount.value).toString() : flight.tdrticket
    };

    await updateFlight(updatedFlight);

    alert('订购成功！');
    orderDialogVisible.value[index] = false;

    // Update local flight data
    flights.value[index] = { ...flight, ...updatedFlight };

  } catch (error) {
    console.error('Error creating order or updating flight:', error);
    alert('订购失败，请稍后再试。');
  }
};

const formatTime = (time) => {
  const date = new Date(time);
  return `${date.getHours()}:${date.getMinutes()}`;
};

const calculateDuration = (start, end) => {
  const startDate = new Date(start);
  const endDate = new Date(end);
  const duration = endDate - startDate;
  const hours = Math.floor(duration / 3600000);
  const minutes = Math.floor((duration % 3600000) / 60000);
  return `${hours}小时${minutes}分钟`;
};
</script>

<style scoped>
.flight-list {
  margin-top: 20px;
}

.flight-card {
  margin-bottom: 20px;
}

.flight-info {
  display: flex;
  align-items: center;
  padding: 10px;
}

.airline-logo {
  width: 50px;
  height: auto;
  margin-right: 20px;
}

.flight-details {
  display: flex;
  flex-grow: 1;
  justify-content: space-between;
  align-items: center;
}

.flight-main-info {
  display: flex;
  flex-direction: column;
}

.flight-main-info h4 {
  margin: 0;
  font-size: 18px;
}

.flight-main-info p {
  margin: 5px 0;
}

.price {
  font-size: 18px;
  color: orange;
}

.buttons {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.buttons .el-button {
  margin: 5px 0;
}
</style>
